package com.dd.filter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.TimerTask;
import javax.servlet.ServletContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.StaleObjectStateException;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate.HibernateOptimisticLockingFailureException;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.dd.entity.*;
import com.dd.dao.*;
import com.dd.service.*;

public class OrderTask extends TimerTask {
	private ApplicationContext ctx;
	private static final Log logger = LogFactory.getLog(SystemTimerTask.class);
	private static boolean isRunning = false;
	ServletContext application;

	public OrderTask(ServletContext sc) {
		application = sc;
		this.ctx = WebApplicationContextUtils
				.getRequiredWebApplicationContext(sc);
		System.out.println(" OrderTask start........................");
	}

	public void run() {
		try {
			if (!isRunning) {
				// 未及时支付订单处理
				// 1)根据下单期.如果超过1天未付款,kill;

				DdOrderDAO dod = (DdOrderDAO) ctx.getBean("DdOrderDAO");
				DdShopDAO ddsd = (DdShopDAO) ctx.getBean("DdShopDAO");
				DdSmsDAO dsd = (DdSmsDAO) ctx.getBean("DdSmsDAO");
				DdUserorder1DAO dud1 = (DdUserorder1DAO) ctx
						.getBean("DdUserorder1DAO");
				DdUserorderDAO dud = (DdUserorderDAO) ctx
						.getBean("DdUserorderDAO");
				DdUserDAO dudd = (DdUserDAO) ctx
				.getBean("DdUserDAO");
				DdUserpayDAO dupd = (DdUserpayDAO)ctx.getBean("DdUserpayDAO");
				Calendar cal = Calendar.getInstance();// 使用默认时区和语言环境获得一个日历。
				cal.add(Calendar.DAY_OF_MONTH, -1);// 取当前日期的前一天.
				// 通过格式化输出日期
				java.text.SimpleDateFormat format = new java.text.SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String datestr = format.format(cal.getTime());
				// System.out.println(datestr);
				List list = dod.findNotPay(datestr);
				// System.out.println(list.size());
				for (int i = 0; i < list.size(); i++) {
					DdOrder ddorder = (DdOrder) list.get(i);
					ddorder.setStatus(-3);
					ddorder.setRemark(ddorder.getRemark()
							+ " ---超出下单期一天未付款.订单被系统取消.");
					dod.save(ddorder);
				}
				// 商家未及时确认订单
				// 1)定位根据预计客服付款时间.如果当前时间超过付款时间20分钟算商家取消(不保存到满座信息表);
				// 2)定礼品根据预计客服付款时间.如果当前时间超过付款时间20分钟算商家取消;
//				cal = Calendar.getInstance();// 使用默认时区和语言环境获得一个日历。
//				cal.add(Calendar.MINUTE, -20);// 取20分钟之前日期
//				datestr = format.format(cal.getTime());
//				// System.out.println(datestr);
//				list = dod.findNotConfirmS(datestr);
//				// System.out.println(list.size());
//				for (int i = 0; i < list.size(); i++) {
//					DdOrder ddorder = (DdOrder) list.get(i);
//					ddorder.setStatus(-3);
//					ddorder.setRemark(ddorder.getRemark()
//							+ " ---商家未及时确认.订单被系统取消.");
//					dod.save(ddorder);
//					String phone = "";
//					String name="";
//					if (ddorder.getType().intValue() == 2) {
//						// 定位
//						DdUserorder1 duo = (DdUserorder1) dud1.findByOrderid(
//								ddorder.getId()).get(0);
//						phone = duo.getPhone();
//						name=duo.getName() + (duo.getSex() == 0 ? "小姐" : "先生");
//					} else {
//						DdUserorder duo = (DdUserorder) dud.findByOrderid(
//								ddorder.getId()).get(0);
//						name=duo.getName2() + (duo.getSex2() == 0 ? "小姐" : "先生");
//						phone = duo.getPhone2();
//					}
//					DdSms dsms = new DdSms();
//					dsms.setSendmsg("【蛋订网】"+name+"您的订单:"+(ddorder.getId()+100000000+"")+"  被商家取消,订金已退回到您的网站账户，给您带来的不便请见谅。");
//					dsms.setOrderid(ddorder.getId());
//					dsms.setOrderstatus(-3);
//					dsms.setTypes(2);
//					dsms.setStatus(0);
//					dsms.setPhone(phone);
//					dsd.saveOrUpdate(dsms);
//					// 取消订单,退款
//					DdUserpay up = dupd.findByOrderid(
//							ddorder.getId(), 2);
//					DdUserpay up_tmp = dupd.findByOrderid(
//							ddorder.getId(), -2);
//					if (up_tmp == null&&up!=null) { // 未退款
//						DdUser du = dudd.findById(up.getUserid());
//						du.setAmount(du.getAmount() + up.getAmount());
//						du.setAmountfree(du.getAmountfree()
//								+ up.getAmountfree());
//						dudd.saveOrUpdate(du);
//						// 新建个退款的userpay,直接把定金原路返回到user中,真实币与虚拟币分开计算
//						DdUserpay up1 = new DdUserpay();
//						up1.setUserid(du.getId());
//						up1.setOrderid(ddorder.getId());
//						up1.setPaydate(new Date());
//						up1.setPaytype(-2);
//						up1.setStatus(2);
//						up1.setAmount(up.getAmount());
//						up1.setAmountfree(up.getAmountfree());
//						up1.setShopid(up.getShopid());
//						up1.setRemark(up.getRemark());
//						dupd.saveOrUpdate(up1);
//					}
//				}
				// 用户未及时确认订单处理
				// 1)定位根据预计到达时间.如果当前时间超过到达时间3天自动确认(不给积分)
				// 2)定礼品根据预计送达时间.如果当前时间超过送达时间3天自动确认(不给积分)
				cal = Calendar.getInstance();// 使用默认时区和语言环境获得一个日历。
				cal.add(Calendar.DAY_OF_MONTH, -3);// 取3天前日期
				datestr = format.format(cal.getTime());
				list = dod.findNotConfirmU2(datestr);
				for (int i = 0; i < list.size(); i++) {
					Object[] obj = (Object[]) list.get(i);
					DdOrder ddorder = (DdOrder) obj[0];
					ddorder.setStatus(3);
					ddorder.setScore(10);
					DdShop ds = ddsd.findById(ddorder.getShopid());
					ds.setScore(ds.getScore()+10);
					ddsd.saveOrUpdate(ds);
					ddorder.setRemark(ddorder.getRemark()
							+ " ---用户未及时确认订单成功.订单被系统自动确认成功.");
					ddorder.setConfirmdate(new Date());
					dod.save(ddorder);
				}

				list = dod.findNotConfirmU1(datestr);
				for (int i = 0; i < list.size(); i++) {
					Object[] obj = (Object[]) list.get(i);
					DdOrder ddorder = (DdOrder) obj[0];
					ddorder.setStatus(3);
					ddorder.setStatus(3);
					ddorder.setScore(10);
					DdShop ds = ddsd.findById(ddorder.getShopid());
					ds.setScore(ds.getScore()+10);
					ddsd.saveOrUpdate(ds);
					ddorder.setRemark(ddorder.getRemark()
							+ " ---用户未及时确认订单成功.订单被系统自动确认成功.");
					ddorder.setConfirmdate(new Date());
					dod.save(ddorder);
				}

				isRunning = true;
			} else {
				logger.info("[OrderTask]-The last task is not over");
			}
			isRunning = false;

		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error(e.toString());
			isRunning = false;
		}

	}
}
